package com.base.study.activity;

import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.base.adapter.BaseAdapter;
import com.base.commonlib.base.adapter.BaseHolder;
import com.base.commonlib.resh.api.RefreshLayout;
import com.base.commonlib.resh.footer.ClassicsFooter;
import com.base.commonlib.resh.header.ClassicsHeader;
import com.base.commonlib.resh.listener.OnRefreshLoadmoreListener;
import com.base.commonlib.utils.DragImageUtils;
import com.base.commonlib.utils.SubStringUtil;
import com.base.commonlib.utils.ToastUtil;
import com.base.commonlib.widget.CommonDialog;
import com.base.commonlib.widget.SingleChooseDialog;
import com.base.commonlib.widget.SingleSearchDialog;
import com.base.study.R;
import com.base.study.bean.QuestionType;
import com.base.study.bean.SubjectListBean;
import com.base.study.bean.TestPaperTypeBean;
import com.base.study.databinding.ActivityTestPaperTypeListBinding;
import com.base.study.presenter.TestPaperTypeListPresenter;
import com.base.study.view.TestPaperTypeListView;
import com.base.study.widget.RecyclerViewSpacesItemDecoration;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


@Route(path = "/sublect/list")
public class TestPaperTypeListActivity extends CBaseBarMvpActivity<TestPaperTypeListPresenter> implements TestPaperTypeListView {
    private ActivityTestPaperTypeListBinding mBinding;
    private SingleSearchDialog singBigleSearchDialog;
    private SingleSearchDialog singSmallleSearchDialog;
    private List<SubjectListBean.Rows> mData = new ArrayList<>();
    @Autowired
    public String parentId;
    @Autowired
    public String subjectId;
    @Autowired
    public String parentName;
    @Autowired
    public String subjectName;
    private BaseAdapter<SubjectListBean.Rows> mAdapter;
    private int page = 1;
    private final String QUESTION_TYPE_ID = "b14e493edf8b470dac4e4039a4392d77";
    private String typeId = "";
    private int starTime = 0;
    private int addTime = 0;
    public static final int START_VAILD = 1;//验证
    public static final int ADD_VAILD = 2;//加分
    public static final int START_STUDY = 3;//计时器
    public static final int IS_SHOW_TIME = 4;//验证是否显示
    public int studyTime = 0;
    public int endTime = new Random().nextInt(MINIESSS);
    public boolean isShowTime;

    public static final int MINIESSS = 600;
    DragImageUtils dragImageUtils;

    //计时器
    public Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case START_VAILD:
                    starTime++;
                    if (starTime == endTime) {
                        //endTime
                        starTime = 0;
                        endTime = new Random().nextInt(MINIESSS);
                        //验证
                        if (mBinding.smartRefreshLayout != null) {
                            mHandler.removeMessages(ADD_VAILD);
                            mHandler.removeMessages(START_STUDY);
                            isShowTime = true;
                            dragImageUtils = new DragImageUtils();
                            dragImageUtils.showDragImageVaild(mBinding.smartRefreshLayout, TestPaperTypeListActivity.this, mHandler);
                        }
                    } else {
                        mHandler.sendEmptyMessageDelayed(START_VAILD, 1000);
                    }
                    break;
                case ADD_VAILD:
                    addTime++;
                    if (addTime == MINIESSS) {
                        //十分钟
                        addTime = 0;
                        if ("3aceee33bad7446698b5b493928c3c75".equals(mPresenter.mUser.getTenantId())) {
                            mPresenter.getJifeng(parentId, mPresenter.mUser.getTenantId());
                        }

                        mHandler.sendEmptyMessageDelayed(ADD_VAILD, 1000);
                    } else {
                        mHandler.sendEmptyMessageDelayed(ADD_VAILD, 1000);
                    }
                    break;
                case START_STUDY:
                    studyTime++;

                    mBinding.timeStr.setText(studyTime + "秒");
                    mHandler.sendEmptyMessageDelayed(START_STUDY, 1000);
                    break;
                case IS_SHOW_TIME:
                    isShowTime = false;
                    break;
            }
        }
    };

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_test_paper_type_list;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityTestPaperTypeListBinding) mRootBinding;
        mBinding.smartRefreshLayout.setRefreshHeader(new ClassicsHeader(mContext));
        mBinding.smartRefreshLayout.setHeaderHeight(60);
        mBinding.smartRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        mPresenter = new TestPaperTypeListPresenter(this, this);
        mPresenter.start();
        if (!TextUtils.isEmpty(parentName)) {
            mBinding.big.setText(parentName + "");
        }
        if (!TextUtils.isEmpty(subjectName)) {
            mBinding.small.setText(subjectName + "");
        }

        //获取大类
        mPresenter.getBigTypeList(1, 10, "0", mPresenter.mUser.getTenantId());
    }

    @Override
    protected void start() {
        setBackNavigationTip(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mBinding.timeStr.equals("0秒")) {
                    finish();
                } else {
                    CommonDialog dialog = new CommonDialog(mContext, "您确定要退出学习吗？", "提示", "取消", "确定");
                    dialog.setOnPosClick(new CommonDialog.OnPosClick() {
                        @Override
                        public void onClick() {
                            finish();
                        }
                    });
                    dialog.show();
                }
            }
        });
        setBarTitle("题库");
        mAdapter = new BaseAdapter<SubjectListBean.Rows>(mData, mContext, true) {

            @Override
            public void convert(BaseHolder holder, final SubjectListBean.Rows subjectListBean, boolean isHeader, boolean isBottom) {
                TextView title = holder.getView(R.id.text1);
                TextView type = holder.getView(R.id.text_type);
                TextView text3 = holder.getView(R.id.text3);
                TextView text4 = holder.getView(R.id.text4);
                TextView textDate = holder.getView(R.id.text_date);
                title.setText(subjectListBean.getItemName());
                type.setText(subjectListBean.getQuestionsType());
                text3.setText(subjectListBean.getRootSubjectName());
                text4.setText(subjectListBean.getSubjectName());

                StringBuilder stringBuilder = null;

                if ("单选题".equals(subjectListBean.getQuestionsType())) {
                    stringBuilder = new StringBuilder();
//                    stringBuilder.append(subjectListBean.getPickFruits());
//                    stringBuilder.append("：");
                    if ("A".equals(subjectListBean.getPickFruits())) {
                        stringBuilder.append(subjectListBean.getAnswerOne());
                    }
                    if ("B".equals(subjectListBean.getPickFruits())) {
                        stringBuilder.append(subjectListBean.getAnswerTwo());
                    }
                    if ("C".equals(subjectListBean.getPickFruits())) {
                        stringBuilder.append(subjectListBean.getAnswerThree());
                    }
                    if ("D".equals(subjectListBean.getPickFruits())) {
                        stringBuilder.append(subjectListBean.getAnswerFour());
                    }
                    if ("E".equals(subjectListBean.getPickFruits())) {
                        stringBuilder.append(subjectListBean.getAnswerFive());
                    }
                    if ("F".equals(subjectListBean.getPickFruits())) {
                        stringBuilder.append(subjectListBean.getAnswerSix());
                    }
                    textDate.setText(stringBuilder.toString());
                    //textDate.setText(subjectListBean.getJudgePickFruits()+subjectListBean.getAnswerTwo());
                }
//                if ("单选题".equals(subjectListBean.getQuestionsType())) {
//                    textDate.setText("参考答案：" + subjectListBean.getPickFruits());
//                }
                else if ("多选题".equals(subjectListBean.getQuestionsType())) {
                    stringBuilder = new StringBuilder();

                    if (subjectListBean.getMultiSelectFruits().contains("A")) {
                        stringBuilder.append(subjectListBean.getAnswerOne());
                        stringBuilder.append("\n");

                    }
                    if (subjectListBean.getMultiSelectFruits().contains("B")) {
                        stringBuilder.append(subjectListBean.getAnswerTwo());
                        stringBuilder.append("\n");

                    }
                    if (subjectListBean.getMultiSelectFruits().contains("C")) {
                        stringBuilder.append(subjectListBean.getAnswerThree());
                        stringBuilder.append("\n");

                    }
                    if (subjectListBean.getMultiSelectFruits().contains("D")) {
                        stringBuilder.append(subjectListBean.getAnswerFour());
                        stringBuilder.append("\n");


                    }
                    if (subjectListBean.getMultiSelectFruits().contains("E")) {
                        stringBuilder.append(subjectListBean.getAnswerFive());
                        stringBuilder.append("\n");

                    }
                    if (subjectListBean.getMultiSelectFruits().contains("F")) {
                        stringBuilder.append(subjectListBean.getAnswerSix());

                    }
                    textDate.setText(stringBuilder.toString());
                }
                if ("判断题".equals(subjectListBean.getQuestionsType())) {
                    textDate.setText(subjectListBean.getJudgePickFruits());
                }

            }
        };
        mBinding.timeStr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.showTimeDetail(mBinding.timeStr);
            }
        });

        mAdapter.putNormalType(R.layout.item_test_paper_type_list);
        mAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseHolder holder, int dataPosition, boolean isHeader, boolean isBottom) {
                SubjectListBean.Rows rows = mData.get(dataPosition);
                ARouter.getInstance().build("/subject/test_typedetail")
                        .withString("rows", new Gson().toJson(rows))
                        .navigation();
            }
        });
        mBinding.rvTestTypeList.setAdapter(mAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        mBinding.rvTestTypeList.setLayoutManager(linearLayoutManager);
        mBinding.rvTestTypeList.addItemDecoration(new RecyclerViewSpacesItemDecoration
                (10, 10, 10, 10));
        mBinding.smartRefreshLayout.autoRefresh();
        mBinding.smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                mPresenter.getList(page, 10, parentId, subjectId, typeId);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                mPresenter.getList(page, 10, parentId, subjectId, typeId);
            }
        });


        mBinding.linBig.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTestPaperTypeBean != null) {
                    singBigleSearchDialog = new SingleSearchDialog(mContext, "选择大类", mTestPaperTypeBean.getRows(), new SingleSearchDialog.OnItemChooseListener() {
                        @Override
                        public void onItemChoose(Object o) {
                            if (o instanceof TestPaperTypeBean.Rows) {
                                TestPaperTypeBean.Rows typeBean = (TestPaperTypeBean.Rows) o;
                                parentId = typeBean.getId();
                                mBinding.big.setText(SubStringUtil.subStringCN(typeBean.getTestQuestions(), 12));
                                mPresenter.getList(1, 10, parentId, subjectId, typeId);
                                mPresenter.getSmallTypeList(1, 10, parentId, mPresenter.mUser.getTenantId());
                            }

                        }
                    });
                    if (singBigleSearchDialog != null) {
                        singBigleSearchDialog.show();
                    }
                }


            }
        });
        mBinding.linSmall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(parentId)) {
                    ToastUtil.show("请先选择大类");
                    return;
                }

                if (mTestPaperTypeSmallBean != null) {
                    singSmallleSearchDialog = new SingleSearchDialog(mContext, "选择小类", mTestPaperTypeSmallBean.getRows(), new SingleSearchDialog.OnItemChooseListener() {
                        @Override
                        public void onItemChoose(Object o) {
                            if (o instanceof TestPaperTypeBean.Rows) {
                                TestPaperTypeBean.Rows typeBean = (TestPaperTypeBean.Rows) o;
                                mBinding.small.setText(SubStringUtil.subStringCN(typeBean.getTestQuestions(), 12));
                                subjectId = typeBean.getId();
                                page = 1;
                                mPresenter.getList(page, 10, parentId, subjectId, typeId);
                            }

                        }
                    });
                    if (singSmallleSearchDialog != null) {
                        singSmallleSearchDialog.show();
                    }
                }


            }
        });

        //获取题目类型
        mBinding.linType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.getType(1, 10, QUESTION_TYPE_ID);
            }
        });
    }

    private TestPaperTypeBean mTestPaperTypeBean;

    @Override
    public void returnBigTypeList(TestPaperTypeBean testPaperTypeBean) {
        mTestPaperTypeBean = testPaperTypeBean;
        //获取小类
        if (mTestPaperTypeBean != null) {
            if (mTestPaperTypeBean.getRows().size() > 0) {
//                for (int i = 0; i <mTestPaperTypeBean.getRows().size() ; i++) {
//                    if (parentId.equals(mTestPaperTypeBean.getRows().get(i).getId())){
//                        mBinding.big.setText(SubStringUtil.subStringCN(mTestPaperTypeBean.getRows().get(i).getTestQuestions(), 12));
//                    }
//                }

//                parentId= mTestPaperTypeBean.getRows().get(0).getId();
//                mBinding.big.setText(SubStringUtil.subStringCN(mTestPaperTypeBean.getRows().get(0).getTestQuestions(), 12));
//                mPresenter.getSmallTypeList(1, 20, parentId);
            }
        }

    }

    private TestPaperTypeBean mTestPaperTypeSmallBean;

    @Override
    public void returnSmallTypeList(TestPaperTypeBean testPaperTypeBean) {
        mTestPaperTypeSmallBean = testPaperTypeBean;
        if (mTestPaperTypeSmallBean != null) {
//            for (int i = 0; i <mTestPaperTypeSmallBean.getRows().size() ; i++) {
//                if (subjectId.equals(mTestPaperTypeSmallBean.getRows().get(i).getId())){
//                    mBinding.small.setText(SubStringUtil.subStringCN(mTestPaperTypeSmallBean.getRows().get(i).getTestQuestions(), 12));
//                }
//            }
//                parentId= mTestPaperTypeBean.getRows().get(0).getId();
//                mBinding.big.setText(SubStringUtil.subStringCN(mTestPaperTypeBean.getRows().get(0).getTestQuestions(), 12));
//                mPresenter.getSmallTypeList(1, 20, parentId);
        }
//            if (mTestPaperTypeSmallBean.getRows().size()>0){
//                mBinding.small.setText(SubStringUtil.subStringCN(mTestPaperTypeSmallBean.getRows().get(0).getTestQuestions(), 12));
//                subjectId = mTestPaperTypeSmallBean.getRows().get(0).getId();
//                mPresenter.getList(1,10,parentId,subjectId,typeId);
//            }

    }

    private SingleChooseDialog typeSearchDialog;

    @Override
    public void returnQuestionTypeList(QuestionType questionType) {
        if (questionType != null) {
            /**
             *  选择题目类型
             */
            typeSearchDialog = new SingleChooseDialog(mContext, "选择题目类型", questionType.getRows(), new SingleChooseDialog.OnItemChooseListener() {
                @Override
                public void onItemChoose(Object o) {
                    page = 1;
                    if (o instanceof QuestionType.Rows) {
                        QuestionType.Rows questionType = (QuestionType.Rows) o;
                        typeId = questionType.getTypeId();
                        mBinding.type.setText(SubStringUtil.subStringCN(questionType.getType(), 12));
                        mPresenter.getList(1, 10, parentId, subjectId, typeId);
                    }


                }
            });
            if (typeSearchDialog != null) {
                typeSearchDialog.show();
            }
        }

    }


    @Override
    public void returnError() {
    }

    @Override
    public void returnList(SubjectListBean subjectListBean) {
        mBinding.empty.setVisibility(View.GONE);
        mBinding.smartRefreshLayout.finishRefresh();
        mBinding.smartRefreshLayout.setLoadmoreFinished(false);
        mData.clear();
        mData.addAll(subjectListBean.getRows());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void returnMoreList(SubjectListBean subjectListBean) {
        mBinding.empty.setVisibility(View.GONE);
        mBinding.smartRefreshLayout.finishLoadmore();
        mBinding.smartRefreshLayout.setLoadmoreFinished(false);
        mData.addAll(subjectListBean
                .getRows());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void returnNoMoreData() {
        mBinding.empty.setVisibility(View.GONE);
        mBinding.smartRefreshLayout.finishLoadmore();
        mBinding.smartRefreshLayout.setLoadmoreFinished(true);
    }

    @Override
    public void returnNoData() {
        mData.clear();
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        mBinding.smartRefreshLayout.finishRefresh();
        mBinding.empty.setVisibility(View.VISIBLE);
    }

    @Override
    public void returnListError() {
        mBinding.empty.setVisibility(View.GONE);
        if (page == 1) {
            mBinding.smartRefreshLayout.finishRefresh();
        } else {
            mBinding.smartRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void startStudy() {
        mHandler.sendEmptyMessage(START_VAILD);
        mHandler.sendEmptyMessage(ADD_VAILD);
        mHandler.sendEmptyMessage(START_STUDY);

    }

    @Override
    public String returnStudyTiem() {
        return mPresenter.getHour(studyTime + "");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dragImageUtils != null) {
            dragImageUtils.onDestory();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    @Override
    public void onBackPressedSupport() {
        if (!isShowTime) {
            if (mBinding.timeStr.equals("0秒")) {
                finish();
            } else {
                CommonDialog dialog = new CommonDialog(mContext, "您确定要退出学习吗？", "提示", "取消", "确定");
                dialog.setOnPosClick(new CommonDialog.OnPosClick() {
                    @Override
                    public void onClick() {
                        finish();
                    }
                });
                dialog.show();
            }
        } else {
            showMes("请您验证");
        }

    }
}
